<template>
  <div class="entrust-detail">
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <el-button @click="goBack" :icon="ArrowLeft">返回</el-button>
          <span class="title">委托详情</span>
          <div class="status-badge">
            <el-tag :type="getStatusType(entrustDetail.status)">
              {{ getStatusText(entrustDetail.status) }}
            </el-tag>
          </div>
        </div>
      </template>
      
      <!-- 委托基本信息 -->
      <div class="basic-info">
        <h2 class="entrust-title">{{ entrustDetail.title }}</h2>
        
        <div class="info-grid">
          <div class="info-item">
            <el-icon><User /></el-icon>
            <span class="label">发布者：</span>
            <span class="value">{{ entrustDetail.publisher?.name || '匿名发布' }}</span>
            <el-rate 
              v-if="entrustDetail.publisher?.rating"
              v-model="entrustDetail.publisher.rating" 
              disabled 
              show-score 
              text-color="#ff9900"
              score-template="{value}"
              :max="5"
              :show-text="false"
            />
            <span v-if="entrustDetail.publisher?.rating" class="rating-text">
              {{ entrustDetail.publisher.rating }}分
            </span>
          </div>
          
          <div class="info-item">
            <el-icon><Clock /></el-icon>
            <span class="label">发布时间：</span>
            <span class="value">{{ formatTime(entrustDetail.createTime) }}</span>
          </div>
          
          <div class="info-item">
            <el-icon><Timer /></el-icon>
            <span class="label">截止时间：</span>
            <span class="value" :class="{ 'urgent': isUrgent }">
              {{ formatDeadline(entrustDetail.deadline) }}
            </span>
          </div>
          
          <div class="info-item">
            <el-icon><Location /></el-icon>
            <span class="label">服务地点：</span>
            <span class="value">{{ entrustDetail.location }}</span>
          </div>
          
          <div class="info-item">
            <el-icon><Money /></el-icon>
            <span class="label">报酬：</span>
            <span class="value reward">¥{{ entrustDetail.reward }}</span>
          </div>
          
          <div class="info-item">
            <el-icon><Collection /></el-icon>
            <span class="label">类别：</span>
            <el-tag :type="getCategoryType(entrustDetail.category)" size="small">
              {{ entrustDetail.category }}
            </el-tag>
          </div>
        </div>
      </div>
      
      <!-- 委托详情描述 -->
      <div class="description-section">
        <h3>委托详情</h3>
        <p class="description">{{ entrustDetail.description }}</p>
      </div>
      
      <!-- 图片展示 -->
      <div v-if="entrustDetail.images && entrustDetail.images.length > 0" class="images-section">
        <h3>相关图片</h3>
        <div class="image-list">
          <el-image
            v-for="(image, index) in entrustDetail.images"
            :key="index"
            :src="image"
            fit="cover"
            class="detail-image"
            :preview-src-list="entrustDetail.images"
            :initial-index="index"
          >
            <template #placeholder>
              <div class="image-placeholder">
                <el-icon><Picture /></el-icon>
                <span>加载中...</span>
              </div>
            </template>
            <template #error>
              <div class="image-error">
                <el-icon><PictureFilled /></el-icon>
                <span>加载失败</span>
              </div>
            </template>
          </el-image>
        </div>
      </div>
      
      <!-- 已接受状态显示 -->
      <div v-if="entrustDetail.status === 'accepted'" class="accepted-info">
        <el-alert
          title="委托已被接受"
          type="success"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>受托方：{{ entrustDetail.acceptor?.name }}</p>
            <p>接受时间：{{ formatTime(entrustDetail.acceptTime) }}</p>
          </template>
        </el-alert>
      </div>
      
      <!-- 进行中状态显示 -->
      <div v-if="entrustDetail.status === 'in_progress'" class="progress-info">
        <el-alert
          title="委托进行中"
          type="warning"
          :closable="false"
          show-icon
        >
          <template #default>
            <p>受托方：{{ entrustDetail.acceptor?.name }}</p>
            <p>开始时间：{{ formatTime(entrustDetail.startTime) }}</p>
          </template>
        </el-alert>
      </div>
      
      <!-- 操作按钮区域 -->
      <div class="action-section">
        <!-- 未接受状态的操作 -->
        <div v-if="entrustDetail.status === 'pending'" class="pending-actions">
          <el-button 
            type="primary" 
            size="large"
            :loading="acceptLoading"
            @click="handleAccept"
          >
            接受委托
          </el-button>
          <el-button 
            size="large"
            @click="handleContact"
          >
            联系发布者
          </el-button>
        </div>
        
        <!-- 已接受状态的操作 -->
        <div v-if="entrustDetail.status === 'accepted'" class="accepted-actions">
          <el-button 
            type="success" 
            size="large"
            @click="handleStart"
          >
            开始任务
          </el-button>
          <el-button 
            type="warning" 
            size="large"
            @click="handleCancel"
          >
            取消委托
          </el-button>
        </div>
        
        <!-- 进行中状态的操作 -->
        <div v-if="entrustDetail.status === 'in_progress'" class="progress-actions">
          <el-button 
            type="success" 
            size="large"
            @click="handleComplete"
          >
            完成任务
          </el-button>
          <el-button 
            type="warning" 
            size="large"
            @click="handleReport"
          >
            报告问题
          </el-button>
        </div>
        
        <!-- 已完成状态的操作 -->
        <div v-if="entrustDetail.status === 'completed'" class="completed-actions">
          <el-button 
            type="primary" 
            size="large"
            @click="handleRate"
          >
            评价服务
          </el-button>
          <el-button 
            size="large"
            @click="handleViewRate"
          >
            查看评价
          </el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  ArrowLeft, User, Clock, Timer, Location, Money, 
  Collection, Picture, PictureFilled 
} from '@element-plus/icons-vue'

/**
 * 委托详情页面组件
 * @description 显示委托的详细信息，支持不同状态的操作
 */
const route = useRoute()
const router = useRouter()

// 组件状态
const acceptLoading = ref(false)
const entrustDetail = ref({})

// 模拟委托详情数据
const mockDetail = {
  id: 1,
  title: '代取快递',
  category: '快递',
  reward: 15,
  description: '顺丰快递到南门，送到宿舍3号楼，包裹不大，轻便。请帮忙取一下，谢谢！',
  createTime: '2023-11-30T10:30:00Z',
  deadline: '2023-11-30T18:00:00Z',
  location: '南校区快递站 → 宿舍3号楼',
  status: 'pending', // pending, accepted, in_progress, completed, cancelled
  publisher: {
    name: '张同学',
    avatar: '',
    rating: 4.2
  },
  images: [
    'https://via.placeholder.com/300x200/3498db/ffffff?text=快递站位置',
    'https://via.placeholder.com/300x200/e74c3c/ffffff?text=包裹信息'
  ],
  acceptor: null,
  acceptTime: null,
  startTime: null,
  completeTime: null
}

/**
 * 获取状态对应的类型
 * @param {string} status - 状态
 * @returns {string} 标签类型
 */
const getStatusType = (status) => {
  const typeMap = {
    'pending': 'info',
    'accepted': 'warning',
    'in_progress': 'primary',
    'completed': 'success',
    'cancelled': 'danger'
  }
  return typeMap[status] || 'info'
}

/**
 * 获取状态对应的文本
 * @param {string} status - 状态
 * @returns {string} 状态文本
 */
const getStatusText = (status) => {
  const textMap = {
    'pending': '待接受',
    'accepted': '已接受',
    'in_progress': '进行中',
    'completed': '已完成',
    'cancelled': '已取消'
  }
  return textMap[status] || '未知状态'
}

/**
 * 获取类别对应的标签类型
 * @param {string} category - 委托类别
 * @returns {string} 标签类型
 */
const getCategoryType = (category) => {
  const typeMap = {
    '外卖': 'success',
    '快递': 'primary',
    '打印': 'warning',
    '其他': 'info'
  }
  return typeMap[category] || 'info'
}

/**
 * 格式化时间显示
 * @param {string} timeStr - 时间字符串
 * @returns {string} 格式化后的时间
 */
const formatTime = (timeStr) => {
  if (!timeStr) return '未知'
  const time = new Date(timeStr)
  return time.toLocaleString('zh-CN')
}

/**
 * 格式化截止时间
 * @param {string} deadlineStr - 截止时间字符串
 * @returns {string} 格式化后的截止时间
 */
const formatDeadline = (deadlineStr) => {
  if (!deadlineStr) return '未知'
  const deadline = new Date(deadlineStr)
  const now = new Date()
  const diff = deadline - now
  
  if (diff < 0) {
    return '已过期'
  }
  
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const minutes = Math.floor(diff / (1000 * 60))
  
  if (hours > 0) {
    return `${hours}小时后`
  } else {
    return `${minutes}分钟后`
  }
}

/**
 * 判断是否紧急
 */
const isUrgent = computed(() => {
  if (!entrustDetail.value.deadline) return false
  const deadline = new Date(entrustDetail.value.deadline)
  const now = new Date()
  const diff = deadline - now
  return diff > 0 && diff < 2 * 60 * 60 * 1000 // 2小时内
})

/**
 * 获取委托详情
 */
const fetchEntrustDetail = async () => {
  try {
    // TODO: 调用API获取委托详情
    // const res = await getEntrustDetail(route.params.id)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    entrustDetail.value = { ...mockDetail }
    
  } catch (error) {
    console.error('获取委托详情失败：', error)
    ElMessage.error('获取委托详情失败')
  }
}

/**
 * 处理接受委托
 */
const handleAccept = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要接受"${entrustDetail.value.title}"这个委托吗？`,
      '确认接受',
      {
        confirmButtonText: '确定接受',
        cancelButtonText: '取消',
        type: 'info'
      }
    )
    
    acceptLoading.value = true
    
    // TODO: 调用API接受委托
    // await acceptEntrust(entrustDetail.value.id)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    // 更新状态
    entrustDetail.value.status = 'accepted'
    entrustDetail.value.acceptor = {
      name: '当前用户',
      avatar: ''
    }
    entrustDetail.value.acceptTime = new Date().toISOString()
    
    ElMessage.success('委托接受成功！')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('接受委托失败：', error)
      ElMessage.error('接受委托失败')
    }
  } finally {
    acceptLoading.value = false
  }
}

/**
 * 处理联系发布者
 */
const handleContact = () => {
  ElMessage.info('联系功能开发中...')
}

/**
 * 处理开始任务
 */
const handleStart = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要开始执行这个委托任务吗？',
      '确认开始',
      {
        confirmButtonText: '确定开始',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    // TODO: 调用API开始任务
    // await startEntrust(entrustDetail.value.id)
    
    entrustDetail.value.status = 'in_progress'
    entrustDetail.value.startTime = new Date().toISOString()
    
    ElMessage.success('任务已开始！')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('开始任务失败：', error)
      ElMessage.error('开始任务失败')
    }
  }
}

/**
 * 处理取消委托
 */
const handleCancel = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要取消这个委托吗？取消后需要双方确认。',
      '确认取消',
      {
        confirmButtonText: '确定取消',
        cancelButtonText: '继续执行',
        type: 'warning'
      }
    )
    
    // TODO: 调用API取消委托
    // await cancelEntrust(entrustDetail.value.id)
    
    ElMessage.success('取消申请已提交，等待对方确认')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消委托失败：', error)
      ElMessage.error('取消委托失败')
    }
  }
}

/**
 * 处理完成任务
 */
const handleComplete = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要标记任务为完成吗？',
      '确认完成',
      {
        confirmButtonText: '确定完成',
        cancelButtonText: '取消',
        type: 'success'
      }
    )
    
    // TODO: 调用API完成任务
    // await completeEntrust(entrustDetail.value.id)
    
    entrustDetail.value.status = 'completed'
    entrustDetail.value.completeTime = new Date().toISOString()
    
    ElMessage.success('任务已完成！')
    
  } catch (error) {
    if (error !== 'cancel') {
      console.error('完成任务失败：', error)
      ElMessage.error('完成任务失败')
    }
  }
}

/**
 * 处理报告问题
 */
const handleReport = () => {
  ElMessage.info('问题报告功能开发中...')
}

/**
 * 处理评价服务
 */
const handleRate = () => {
  router.push(`/campus-entrust/rate/${entrustDetail.value.id}`)
}

/**
 * 处理查看评价
 */
const handleViewRate = () => {
  router.push(`/campus-entrust/rate-detail/${entrustDetail.value.id}`)
}

/**
 * 返回上一页
 */
const goBack = () => {
  router.go(-1)
}

// 组件挂载时获取数据
onMounted(() => {
  fetchEntrustDetail()
})
</script>

<style scoped>
.entrust-detail {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.detail-card {
  max-width: 800px;
  margin: 0 auto;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 16px;
}

.title {
  flex: 1;
  font-size: 18px;
  font-weight: 600;
}

.status-badge {
  margin-left: auto;
}

.basic-info {
  margin-bottom: 32px;
}

.entrust-title {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 24px;
}

.info-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 8px;
}

.info-item .label {
  font-weight: 500;
  color: #606266;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
  flex: 1;
}

.info-item .reward {
  color: #f56c6c;
  font-weight: 600;
  font-size: 16px;
}

.info-item .urgent {
  color: #e6a23c;
  font-weight: 600;
}

.rating-text {
  font-size: 12px;
  color: #909399;
}

.description-section {
  margin-bottom: 32px;
}

.description-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.description {
  color: #606266;
  line-height: 1.6;
  font-size: 16px;
}

.images-section {
  margin-bottom: 32px;
}

.images-section h3 {
  font-size: 18px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
}

.image-list {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.detail-image {
  width: 200px;
  height: 150px;
  border-radius: 8px;
  cursor: pointer;
}

.image-placeholder,
.image-error {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #909399;
  font-size: 14px;
}

.accepted-info,
.progress-info {
  margin-bottom: 32px;
}

.action-section {
  display: flex;
  gap: 16px;
  justify-content: center;
  padding-top: 24px;
  border-top: 1px solid #ebeef5;
}

.pending-actions,
.accepted-actions,
.progress-actions,
.completed-actions {
  display: flex;
  gap: 16px;
}

@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .image-list {
    justify-content: center;
  }
  
  .detail-image {
    width: 150px;
    height: 112px;
  }
  
  .action-section {
    flex-direction: column;
  }
  
  .pending-actions,
  .accepted-actions,
  .progress-actions,
  .completed-actions {
    flex-direction: column;
  }
}
</style> 